<?php
/* Kammerath Network Website System */
require_once("config.php");

// external lib: Smarty Template Engine
require_once("lib/Smarty/Smarty.class.php");

// external lib: Minify Classes incl. JSMin
require_once("lib/Minify/JSMin.class.php");
require_once("lib/Minify/Minify_HTML.class.php");
require_once("lib/Minify/Minify_Javascript.class.php");

// application internal classes
require_once("class/cache.class.php");
require_once("class/database.class.php");
require_once("class/blog.class.php");
require_once("class/facebook.class.php");
require_once("class/search.class.php");
require_once("class/amazon.class.php");
require_once("class/analytics.class.php");
require_once("class/minify.class.php");

/* output gzip enable, when gzip is accepted */
if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')){
	// client accepts gzip, so gzip the content
	ob_start("ob_gzhandler");
}else{ 
	// continue normally when gzip is unsupported
	ob_start();
}

// create and instance of the blog
// which requires the domain as a param
// to determine the site to use
$b = new blog($_SERVER["HTTP_HOST"]);

/* check if the host name requested is the 
 * primary host name and not one of the CDN 
 * host names */
if($_SERVER["HTTP_HOST"]!=CONFIG_CDN_PRIMARY_DOMAIN){
	// 301 redirect and exit, when it is not 
	// the primary domain name and make sure
	// it is redirecting to the same page requested	
	header("HTTP/1.1 301 Moved Permanently");
	header("Location: http://"
			.CONFIG_CDN_PRIMARY_DOMAIN
			.$_SERVER["REQUEST_URI"]); 
	
	// exists the this request
	exit();
}

// instanciate the template engine
$template = new Smarty();

// define the is_admin var
$is_admin = false;

// indicator whether the request
// should get a 404 response
$is_404 = false;

/* indicates whether a comment was 
 * just posted with this request or not. 
 * This info will be passed directly to 
 * the analytics*/
$comment_posted = false;

// every page needs the category list
$categoryPublishedList = $b->db->getCategoryPublishedList();

// initialize google analytics
$ga = new analytics();

/* assign the facebook token 
 * when the user is logged in */
$f = new facebook();
if($f->isLoggedIn()){
	// get the facebook user
	$user = $f->getUser();
	
	/* add the user if he is new */
	if($f->isNewUser==true){
		// pushes him into the database
		$b->addFacebookUser($user);
	}
	
	if($b->db->userIsAdmin($user->username)){
		$is_admin = true;
	}
	
	// assign the user to the template
	$template->assign("user",$user);	
}

/* define the page type and use 404 as 
 * the default page type as it will show
 * as default when no other page matches */
$pageType = "404";
$pageItem = "404";
if(strpos($_SERVER["REQUEST_URI"],"index.php")==1){
	// its also index, when its index.php
	$pageType = "index";
	$pageItem = "index";
}else{
	if(array_key_exists("type", $_GET)==true
		&&array_key_exists("item", $_GET)==true){
		// page and item definition are present
		$pageType = $_GET["type"];
		$pageItem = $_GET["item"];
	}
}

/* when the page type is index or category,
 * we need the list of articles */
if($pageType=="index"){
	// get the month for the top articles
	$topArticleMonth = $ga->getReportingMonth();
	
	// declare the top article list
	$topArticleList = array();
	
	// get the raw top articles
	$topArticleListRaw = $ga->getCachedThisMonthsTopArticles
								($topArticleMonth["number"]);

	// take ten pages at max
	if(count($topArticleListRaw)>10){
		$ta_keys = array_keys($topArticleListRaw);
		for($tp=0;$tp<10;$tp++){
			// copy them, one by one
			$topArticleList[$tp] = $topArticleListRaw[$ta_keys[$tp]];
		}
	}else{
		// if its less or equal ten, take them
		$topArticleList = $topArticleListRaw;
	}
	
	// assign the top articles for the homepage
	$template->assign("thisTopArticleMonth",$topArticleMonth["name"]);
	$template->assign("thisMonthTopArticleList",$topArticleList);
	
	// assign the articles for the home page
	$template->assign("articleList",$b->getLatestArticles(20));
}if($pageType=="search"){
	// instanciate the search class
	$s = new search($_SERVER["HTTP_HOST"]);
	
	// get the keyword and replace the - character
	// as it represents a space the user entered and
	// is just used for clean url creation
	$q = str_replace("-", " ", $_GET["item"]);
	
	// execute the search
	$searchResult = $s->searchSite($q);

	// assign the key word and the result
	$template->assign("searchQuery",$q);
	$template->assign("searchResult",$searchResult);
}if($pageType=="category"){
	// if the category item does not exist
	// we need to show the 404 page
	$cat_found = false;
	for($cl=0;$cl<count($categoryPublishedList);$cl++){
		if($categoryPublishedList[$cl]["url"]==$pageItem){
			$cat_found = true;
		}
	}
	
	// set the 404 flag, when category does not exists
	if(!$cat_found){$is_404=true;}
	
	$pageCategoryItem = $b->db->getCategory($pageItem);
	$template->assign("pageCategoryItem",$pageCategoryItem[0]);
	$template->assign("articleList",$b->getCategoryArticles($pageItem));
}if($pageType=="article"){
	// get the article and its comments
	$preview_mode = false;
	if(array_key_exists("p", $_GET)){
		$preview_mode = true;
	}
	$pageArticle = $b->getArticle($pageItem,$preview_mode);
	$pageComments = $b->db->getArticleCommentList($pageItem);
		
	// set the 404 indicator when the article is null
	if($pageArticle==null){
		// set the indicator
		$is_404 = true;
	}else{
		/* check for a deletion request */
		if(array_key_exists("deleteComment", $_POST)){
			if($f->isLoggedIn()){
				$delete_comment_id = $_POST["deleteComment"];
				
				// set author indicator to false by default
				$is_comment_author = false;
				
				// get the facebook user
				$user = $f->getUser();
				
				// check if the user is author
				for($cm=0;$cm<count($pageComments);$cm++){
					if($pageComments[$cm]["id"]==$delete_comment_id
						&& $pageComments[$cm]["user"]==$user->username){
						// this user is author of the comment
						$is_comment_author = true;
					}
				}
				
				// delete when the user is admin or author
				if($is_admin==true || $is_comment_author==true){
					// finally delete the comment
					$b->db->deleteComment($delete_comment_id);
					
					// update the page comments
					$pageComments = $b->db->getArticleCommentList($pageItem);
				}
			}
		}
		
		/* check if a comment is in the post vars */
		if(array_key_exists("comment", $_POST)){
			if($f->isLoggedIn()){
				// get the facebook user
				$user = $f->getUser();
				
				// finally add the comment
				$b->db->addComment($user->username, 
					$_GET["item"], $_POST["comment"]);
					
				// set the indicator to true
				$comment_posted = true;
					
				// update the page comments
				$pageComments = $b->db->getArticleCommentList($pageItem);
			}
		}
		
		// get the page recommendations
		$analyticsPage = "/".$pageItem.".html";
		
		// retrieve the recommendations cached
		$recommendationList = $ga->getCachedRecommendations($analyticsPage);
	
		// get the amazon book suggestions 
		// for this article when a keyword
		// was provided
		$bookOffers = array();

		if(strlen($pageArticle["keyword"])>0){
			// instanciate the amazon api wrapper class
			$amzn = new amazon($b->db->getLanguageCode());
			// perform an item search in the books category
			$bookOffers = $amzn->itemSearchCached
					($pageArticle["keyword"], "Books");
		}
		// assign both the article and the
		// comment list to the template
		$template->assign("bookOffers",$bookOffers);
		$template->assign("article",$pageArticle);
		$template->assign("commentList",$pageComments);
		$template->assign("recommendationList",$recommendationList);
	}
}

// assign the blog data to the template
$template->assign("categoryList",$categoryPublishedList);

// pass page type and item to the template
$template->assign("pageType",$pageType);
$template->assign("pageItem",$pageItem);

/* set the 404 indicator when 
 * the page is 404 and also add
 * the proper http response code */
if($pageType=="404" || $is_404==true){
	// sets the flag
	$is_404 = true;
	
	/* the 404 page will show a 
	 * list of all articles */
	$template->assign("articleList",
		$b->getLatestArticles(999999));
	
	// sets the 404 header
	header("HTTP/1.0 404 Not Found");
}

/* assign the variables that indicates 
 * whether the user logged in or not */
if($f->isNewUser==true){
	// the user just logged in
	$template->assign("is_new_user","1");
	$template->assign("is_login_denied","0");
	$template->assign("is_logged_out","0");
}else{
	// the user is either already logged in
	// or is not logged in
	$template->assign("is_new_user","0");
	$template->assign("is_login_denied","0");
	$template->assign("is_logged_out","0");

	// when the user is not logged in check
	// if there is an error report in the url
	if($f->isLoggedIn()==false){
		if(array_key_exists("error_reason", $_GET)){
			if($_GET["error_reason"]=="user_denied"){
				// tell the template to run the analytics
				// code to keep track of login denials
				$template->assign("is_login_denied","1");
			}
		}
	}
	
	// check if there is a logout request
	if(array_key_exists("logout", $_GET)){
		// pass over to the analytics event tracking
		$template->assign("is_logged_out","1");
	}
}

// indicates whether a 
// comment was posted or not
if($comment_posted==true){
	// comment was posted with this request
	$template->assign("comment_posted","1");
}else{
	// no comment was posted with this request
	$template->assign("comment_posted","0");
}

// assign the uqid to the template
$ga = new analytics();
$template->assign("uqid",$ga->getUqId());

// assign the current year for the legal footer
$template->assign("year",date("Y"));

// assign the language code
$template->assign("languageCode",$b->db->getLanguageCode());

// assign the template values
$template->assign("is_404",$is_404);
$template->assign("loggedIn",$f->isLoggedIn());
$template->assign("is_admin",$is_admin);
$template->assign("facebook_redirect_url",$f->REDIRECT_URI);

// assign the minpack version tags to 
// prevent users from using outdated minpacks from their cache
$template->assign("minpack_js_tag",minify::getMinpackTag(CONFIG_MINPACK_JS));
$template->assign("minpack_css_tag",minify::getMinpackTag(CONFIG_MINPACK_CSS));

// attach the CDN host names
$template->assign("cdn_host_js",CONFIG_CDN_JS_DOMAIN);
$template->assign("cdn_host_css",CONFIG_CDN_CSS_DOMAIN);
$template->assign("cdn_host_proxy",CONFIG_CDN_PROXY_DOMAIN);
$template->assign("primary_domain",CONFIG_CDN_PRIMARY_DOMAIN);

// attach the google analytics site data
$template->assign("analytics_account",CONFIG_GA_SITE_ACCOUNT);
$template->assign("analytics_domain",substr(CONFIG_CDN_PRIMARY_DOMAIN, 
								strpos(CONFIG_CDN_PRIMARY_DOMAIN, ".")));

// fetch the content, minify, remove line breaks and output it
$html_output = $template->fetch("themes/desktop/master.tpl");

// set the content type and charset header before output
header("Content-Type: text/html; charset=utf-8");

/* update the image tags with the cdn host names */
$html_output = $b->updateCdnHtml($html_output);

// finally print out the minified html code
print(minify::minifyHtml($html_output));
?>
